<template>
  <div id="app">
    <el-card shadow="always">
      {{carSearch}}
      <el-form :inline="true" size="medium" :model="carSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item >
          <el-input v-model="carSearch.pname" placeholder="汽车名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="carSearch.addr" placeholder="产地"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="carSearch.cid" placeholder="所在车库">
            <el-option label="所有车库" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addStudent">添加车辆</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="carList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="编号"
            prop="pid"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="车名"
            align="center"
            prop="pname">
        </el-table-column>
        <el-table-column
            label="产地"
            align="center"
            prop="addr">
        </el-table-column>
        <el-table-column
            label="所在车库"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{car}}
      <el-form :model="car" :rules="rules" ref="ruleForm">
        <el-form-item label="汽车名" prop="pname" :label-width="formLabelWidth">
          <el-input v-model="car.pname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="产地" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="car.addr" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所在车库" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="car.cid" placeholder="请选择所在车库">
            <el-option label="所有车库" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCar">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import carApi from "@/api/car"
import cangApi from "@/api/cang"
export default {
  data() {

    // let checkAge = (rule, value, callback) => {
    //   if (value === '' || value == null) {
    //     return callback(new Error('年龄不能为空'))
    //   } else if (!Number.isInteger(value)) {
    //     return callback(new Error('年龄必须为数字值'))
    //   } else if (value < 1 || value > 200) {
    //     return callback(new Error('年龄必须在1-200之间'))
    //   } else {
    //     callback()
    //   }
    // }

    return {
      carList: [],
      page:1,
      pageSize:5,
      total:100,
      searchCar:{},
      carSearch: {},
      classesList:[ ],
      dialogFormVisible:false,
      formLabelWidth:'100px',
      car: {},
      title: '添加车辆',
      multipleSelection:[],     // 代表选中的多项
      sids: [],                 // 代表删除的学生编号数组
      rules: {
        pname: [
          {required: true, message: '请输入汽车名', trigger: 'blur'},
        ],
        addr: [
          {required: true, message: '请输入产地', trigger: 'blur'},
        ],
        cid: [
          {required: true, message: '请选择车库', trigger: 'blur'},
        ]
      }

    }
  },created() {
    //this.findCars();
   // this.findByPage()
    this.findAllCang()
    this.search()
  },
  methods: {
    async  findCars(){
      const {data:res} = await carApi.findCars()
      console.log(res.data)
       if(res.code===200){
        this.carList=res.data.list
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      //this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val
      //this.findByPage()
      this.search()
      console.log(`当前页: ${val}`);
    },
    async findByPage(){
      const {data:res} = await carApi.findByPage(this.page,this.pageSize)
      console.log(res)
      this.carList = res.data.pr.rows
      this.total = res.data.pr.total
    },
    async search(){
      const {data:res} = await carApi.search(this.page,this.pageSize,this.carSearch)
      //console.log(res)
      this.carList = res.data.pr.rows
      this.total = res.data.pr.total
    },
    async findAllCang(){
      const {data:res} = await cangApi.findAllCang()
      console.log(res)
      if (res.code === 200) {
        this.classesList = res.data.list
      }
    },
    //11
    saveCar() {
      this.$refs.ruleForm.validate(async valid => {

        let url = "/car/add"      // 默认地址是添加学生
        let method = "post"           // 添加是post请求
        if(this.car.pid){
          url = "/car/update"    // 如果有值就改为修改学生
          method = "put"             // 修改是put请求
        }

        if (valid) {
          const {data:res} = await carApi.save(url,method,this.car)
           console.log("验证通过")
          console.log("res:",res)
          console.log("cars:",this.car)
          if (res.code === 200) {     // 后端执行成功返回200
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {        // 关闭对话框时的回调

                this.dialogFormVisible = false

                this.search()
              }
            })
          }else{                      // 后端执行失败返回500
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    //11
    handleEdit(index, row) {

      this.title = '修改汽车'

      this.car = row

      this.dialogFormVisible = true

      console.log(index, row);
    },
    handleDelete(index, row) {
      this.sids = []
      if(row){  // 代表删除单个学生
        this.sids.push(row.pid)
      }else{
        this.sids = this.multipleSelection.map(m => m.pid)
      }
      console.log("sids:",this.sids)
      console.log(index,row);
      this.$confirm(`是否真的要删除学号为${this.sids}的车辆吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {       // 点击了"确定"按钮后执行
        let _this = this
        carApi.deleteCar(this.sids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {     // 点击了"取消"按钮后执行
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addStudent() {
      this.title = "添加汽车"
      this.car = {}
      this.dialogFormVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

  }
}
</script>

<style>
.el-card{
  width: 90%;
  margin: 0 auto;
}
#app{
  display: flex;
  justify-content: center;
}
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
</style>
